using B.S.NewMedical.Api.Read.Application.Command.Department;
using B.S.NewMedical.Api.Read.DTOS.Department;
using B.S.NewMedical.Domain.Doctor;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.Department
{
    /// <summary>
    /// 获取科室详情处理器
    /// 处理获取科室详情的业务逻辑
    /// </summary>
    public class GetDepartmentDetailHandler : IRequestHandler<GetDepartmentDetailCommand, ApiResult<DepartmentDetailDto>>
    {
        private readonly IBaseRepository<DepartmentModel> _departmentRepository;
        private readonly ILogger<GetDepartmentDetailHandler> _logger;

        /// <summary>
        /// 构造函数
        /// 注入依赖的服务
        /// </summary>
        /// <param name="departmentRepository">科室仓储接口</param>
        /// <param name="logger">日志记录器</param>
        public GetDepartmentDetailHandler(IBaseRepository<DepartmentModel> departmentRepository, ILogger<GetDepartmentDetailHandler> logger)
        {
            _departmentRepository = departmentRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取科室详情命令
        /// 执行获取科室详情的业务逻辑
        /// </summary>
        /// <param name="request">获取科室详情命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>科室详情信息</returns>
        public async Task<ApiResult<DepartmentDetailDto>> Handle(GetDepartmentDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证科室ID
                if (request.Id <= 0)
                {
                    _logger.LogWarning("科室ID无效: {DepartmentId}", request.Id);
                    return new ApiResult<DepartmentDetailDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "科室ID无效"
                    };
                }

                // 查询科室信息
                var department = _departmentRepository.GetAll()
                    .Where(d => d.Id == request.Id && !d.IsDeleted).FirstOrDefault();

                if (department == null)
                {
                    _logger.LogWarning("科室不存在或已被删除: {DepartmentId}", request.Id);
                    return new ApiResult<DepartmentDetailDto>
                    {
                        Code = ApiEnum.Fail,
                        Msg = $"科室ID {request.Id} 不存在或已被删除"
                    };
                }

                // 构建返回的DTO
                var departmentDetail = new DepartmentDetailDto
                {
                    Id = department.Id,
                    DepartmentName = department.DepartmentName,
                    DepartmentAddr = department.DepartmentAddr,
                    RegistrationFee = department.RegistrationFee,
                    Type = department.Type,
                    IsOnline = department.IsOnline,
                    IsEmergencyService = department.IsEmergencyService,
                    ParentId = department.ParetId,
                    Remark = department.remark,
                    CreateTime = department.CreateTime ?? DateTime.Now
                };

                _logger.LogInformation("获取科室详情成功，科室ID: {DepartmentId}, 科室名称: {DepartmentName}", 
                    request.Id, department.DepartmentName);

                return new ApiResult<DepartmentDetailDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取科室详情成功",
                    Data = departmentDetail
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取科室详情时发生异常，科室ID: {DepartmentId}", request.Id);
                return new ApiResult<DepartmentDetailDto>
                {
                    Code = ApiEnum.Error,
                    Msg = $"获取科室详情失败: {ex.Message}"
                };
            }
        }
    }
} 